<?php
/*
 * @Description:数字化追踪管理
 * @FilePath: \auxface_certificate\app\certificate\controller\user\v1\DigitalMachine.php
 */

declare (strict_types = 1);

namespace app\certificate\controller\user\v1;

use think\facade\Db;
use think\Request;

class DigitalMachine
{
    public $table = "certificate_digitalmachine";

    /**
     * @Description:
     * @param {Request} $request
     */
    public function getList(Request $request)
    {
        $data = $request->data;

        $limit = $data['limit'] ?? 10;
        $page  = $data['page'] ?? 1;
        $where = [
            ['projectCode', '=', $request->prjCode],
            ['isDelete', '=', $data['isDelete'] ?? 0],
        ];
        if (!empty($data['machineName'])) {
            array_push($where, ['name', 'like', "%" . $data['machineName'] . "%"]);
        }
        if (!empty($data['machineSn'])) {
            array_push($where, ['machineSn', 'like', "%" . $data['machineSn'] . "%"]);
        }
        if (!empty($data['corpCode'])) {
            array_push($where, ['corpCode', "=", $data['corpCode']]);
        }
        if (!empty($data['machineStatus'])) {
            if ($data['machineStatus'] == 'exit') {
                array_push($where, ['status', '=', "2"]);
            } else if ($data['machineStatus'] == 'entry') {
                array_push($where, ['status', '=', "1"]);
            } else if ($data['machineStatus'] == 'repair') {
                array_push($where, ['isRepair', '=', "1"]);
            }
        }
        if (!empty($data['digitalMacineTypeUuid'])) {
            array_push($where, ['digitalMacineTypeUuid', '=', $data['digitalMacineTypeUuid']]);
        }

        $list = DB::table($this->table)
            ->where($where)
            ->page((int) $page, (int) $limit)
            ->field(['uuid','subtitle', 'image', 'isRepair', 'remark', 'inDate', 'entryDate', 'exitDate', 'status', 'corpCode', 'qrCode', 'machineSn', 'digitalMacineTypeUuid','name'])
            ->orderRaw("CASE
                    WHEN isRepair = 1 THEN 1
                    WHEN status = 1 THEN 2
                    WHEN status = 2 THEN 3
                    ELSE 4
                END")
            ->order('id', 'desc')
            ->group('id')
            ->select()->toArray();

        foreach ($list as $key => &$value) {
            if ($value['isRepair'] == 1) {
                $value['status'] = 3;
            }
            //查询设备的类型 获取 检修流程、许可证、检查表、设备类型名称
            $digitalmachinetype = DB::table('certificate_digitalmachinetype')->where("uuid", $value['digitalMacineTypeUuid'])->field(["repairTypeUuid", "machineRiskTypeUuid", "heavyMachineCheckTypeUuid", 'name'])->find();

            // $value['name'] = $digitalmachinetype['name'].'-'.$value['prjMachineCode'].'號機';

            $value['digitalMachineTypeName'] = $digitalmachinetype['name'];

            //查询设备绑定的驾驶员数量
            $where1 = [
                ["digitalMachineUuid", "=", $value['uuid']],
                ["isDelete", "=", 0],
            ];
            $where2 = [
                ['entryTime', '<>', "0000-00-00 00:00:00"],
                ['exitTime', '=', "0000-00-00 00:00:00"],
                ["projectCode", "=", $request->prjCode],
            ];
            //获取驾驶员姓名
            $drivers                = DB::table('certificate_digitalmachinedriver')->where($where1)->column('wxappUserUuid');
            $value['driver']        = DB::table('certification_projectworker')->whereIn('wxappUserUuid', $drivers)->where($where2)->field('workerName')->select()->toArray();
            $value['driverNumbers'] = count($value['driver']);
        }

        $count = DB::table($this->table)
            ->where($where)
            ->count('id');

        $data = [
            'list'  => $list,
            'count' => $count,
        ];
        return result(SUCCESS, $data, '');
    }

    /**
     * @Description: 获取数据
     * @param {Request} $request
     */
    public function getDetail(Request $request)
    {
        $data  = $request->data;
        $uuid  = $data['uuid'];
        $where = [
            ['dm.projectCode', '=', $request->prjCode],
            ['dm.isDelete', '=', 0],
            ['dm.uuid', '=', $uuid],
        ];
        $data = DB::table($this->table)
            ->alias('dm')
            ->join('certificate_digitalmachinetype dmt', 'dm.digitalMacineTypeUuid = dmt.uuid', 'left')
            ->where($where)
            ->field(['dm.machineSn', 'dm.image', 'dm.subtitle', 'dm.isRepair', 'dm.digitalMacineTypeUuid', 'dm.corpCode', 'dm.name', 'dm.remark', 'dm.uuid', 'dm.qrCode', 'dm.status', 'dm.entryDate', 'dm.exitDate', 'dm.otherInfo', 'dm.inDate', 'dmt.name as digitalMachineTypeName', "dmt.repairTypeUuid", "dmt.machineRiskTypeUuid", "dmt.heavyMachineCheckTypeUuid,dm.swl,dm.prjMachineCode,dm.model"])
            ->find();
        if (empty($data)) {
            return result(SUCCESS, [], '');
        }
        // $data['corpName'] = $this->accordUuidGetData('platform_corpbasicinfo', $data['corpCode'], 'corpCode', 'corpName', $request);
        $data['corpName'] = DB::table('projectinfo_projectcorpinfo')
        ->where([
            'projectCode'=>$request->prjCode,
            'corpCode'=>$data['corpCode'],
        ])->value('corpName');
        $data['machineRiskTypeName']       = $this->accordUuidGetData('certificate_machinerisktype', $data['machineRiskTypeUuid'], 'uuid','name',$request);
        if (!empty($data['otherInfo'])) {
            $data['otherInfo'] = json_decode($data['otherInfo'], true);
        }
        if ($data['isRepair'] == 1) {
            $data['status'] = 3;
        }
        return result(SUCCESS, $data, '');
    }

    /**
     * @Description: 判断是否驾驶员，是的话此设备下可以显示检查表。许可证。检修表的申请按钮
     * @param {Request} $request
     */
    public function checkUserCanApply(Request $request)
    {
        $data  = $request->data;
        $where = [
            ['projectCode', '=', $request->prjCode],
            ['digitalMachineUuid', '=', $data['digitalMachineUuid']],
            ['wxappUserUuid', '=', $data['wxappUserUuid']],
            ['isDelete', '=', 0],
        ];
        $check = DB::table('certificate_digitalmachinedriver')->where($where)->count();
        return result(SUCCESS, $check, '');
    }

    protected function accordUuidGetData($table = '', $uuid = '', $fileName = '', $finalName = '', $request)
    {
        //企业表没有isDelete和projectCode
        if (empty($finalName)) {
            $finalName = $fileName;
        }
        $data = DB::table($table)->where("{$fileName}", $uuid)->field(["{$finalName}"])->find();
        return $data["{$finalName}"] ?? '';
    }

    /**
     * @Description: 获取设备最近的许可证数据 一个许可证关联一个流程 一个流程下有多个表单
     * @param {Request} $request
     */
    public function getDigitalMachineRiskData(Request $request)
    {
        $data  = $request->data;
        $where = [
            ['mr.projectCode', '=', $request->prjCode],
            ['mr.isDelete', '=', 0],
            ['mr.machineUuid', '=', $data['digitalMachineUuid']],
        ];
        $field = [
            'mrt.name as MachineRiskTypeName',
            'mr.uuid',
            'mr.typeUuid',
            'mr.wxappUserUuid',
            'mr.status',
            'mr.reason',
            'mr.flowUuid',
            'mr.flowFormUuid',
        ];
        $result = DB::table('certificate_machinerisk')
            ->alias('mr')
            ->leftJoin("certificate_machinerisktype mrt", 'mrt.uuid = mr.typeUuid')
            ->where($where)
            ->order('mr.id desc')
            ->limit(1)
            ->field($field)
            ->find();

        if (empty($result) || empty($result['flowUuid']) || empty($result['uuid'])) {
            return result(SUCCESS, [], '');
        }

        $riskUuid = $result['uuid'];
        $typeUuid = $result['typeUuid'];

        $where = [
            ['mrr.projectCode', '=', $request->prjCode],
            ['mrr.isDelete', '=', 0],
            ['mrr.riskUuid', '=', $riskUuid],
            ['ff.linkForms', '<>', '[]'],
            ['ff.linkForms', '<>', ''],
        ];

        $list = DB::table('certificate_machineriskrecord')
            ->alias('mrr')
            ->leftJoin("certificate_flowform ff", 'ff.uuid = mrr.flowFormUuid')
            ->where($where)
            ->field(['ff.name', 'mrr.inDate', 'mrr.flowFormUuid', 'mrr.uuid as machineRiskRecordUuid'])
            ->order(['mrr.flowOrder asc'])
            ->select()->toArray();

        $data = [
            'machineRiskData'       => $result,
            'machineRiskRecordData' => $list,

        ];
        return result(SUCCESS, $data, '');

    }

    /**
     * @Description: 获取设备最近的检查数据
     * @param {Request} $request
     */
    public function getDigitalMachineHeavyData(Request $request)
    {
        $data  = $request->data;
        $where = [
            ['projectCode', '=', $request->prjCode],
            ['isDelete', '=', 0],
            ['machineUuid', '=', $data['digitalMachineUuid']],
        ];
        $field = [
            'uuid',
            'typeUuid',
            'wxappUserUuid',
            'status',
            'reason',
            'machineSn',
            'weekStartDate',
            'weekEndDate',
        ];
        $result = DB::table('certificate_heavymachinecheck')->where($where)->order('id desc')->field($field)->find();

        if (empty($result)) {
            return result(SUCCESS, [], '');
        }

        $checkUuid = $result['uuid'];

        $where = [
            ['projectCode', '=', $request->prjCode],
            ['isDelete', '=', 0],
            ['checkUuid', '=', $checkUuid],
        ];

        $allRecords = DB::table('certificate_heavymachinecheckrecord')->where($where)->count();

        $dayRecords = DB::table('certificate_heavymachinecheckrecord')->where($where)->where('type', 1)->count();

        $record = DB::table('certificate_heavymachinecheckrecord')->where($where)->field(['UNIX_TIMESTAMP(inDate) as inDate', 'UNIX_TIMESTAMP(checkDate) as checkDate'])->order('id desc')->limit(1)->find();

        array_push($where, ['checkDate', '>=', date('Y-m-d 00:00:00')]);
        array_push($where, ['checkDate', '<=', date('Y-m-d 59:59:59')]);
        $checkToday = DB::table('certificate_heavymachinecheckrecord')->where($where)->find();
        // 一个设备有两个检查表，一个过期一个审批中，谁近用谁。过期提交次数假如是20次，审批中的是5次，显示累计25次
        $data = [
            'heavyMachineCheckData' => $result, //检查表记录
            'latestCheckDate'       => !empty($record['checkDate']) ? date('Y-m-d', $record['checkDate']) : (!empty($record['inDate']) ? date('Y-m-d', $record['inDate']) : ""), //最近检查时间
            'weekRecords'           => $dayRecords, //周内检查次数
            'todayCheckStatus'      => ($checkToday) ? '已完成' : '未完成', //当天检查状态
            'totalRecordNums'       => $allRecords, //累计检查次数，所有检查record表累计
        ];

        return result(SUCCESS, $data, '');
    }
    /**
     * @Description: 获取设备最近的检修数据
     * @param {Request} $request
     */
    public function getDigitalMachineRepairData(Request $request)
    {
        $data  = $request->data;
        $where = [
            ['projectCode', '=', $request->prjCode],
            ['isDelete', '=', 0],
            ['machineUuid', '=', $data['digitalMachineUuid']],
        ];
        $field = [
            'uuid',
            'title',
            'description',
            'wxappUserUuid',
            'status',
            'reason',
            'flowUuid',
            'flowFormUuid',
            'inDate',
        ];
        $numbers = DB::table('certificate_digitalmachinerepair')->where($where)->count();
        $result  = DB::table('certificate_digitalmachinerepair')->where($where)->order('id desc')->limit(3)->field($field)->select();
        $data    = [
            'repairDatas' => $result,
            'numbers'     => $numbers,
        ];
        return result(SUCCESS, $data, '');
    }

    /**
     * @Description: 根据用户UUID获取绑定的设备【实际情况是一个驾驶员可以绑定多个machineSn】
     * @param {Request} $request
     */
    public function accordWorkerUuidGetDigitalMachine(Request $request)
    {
        $data  = $request->data;
        $limit = $data['limit'] ?? 10;
        $page  = $data['page'] ?? 1;
        $where = [
            ['projectCode', '=', $request->prjCode],
            ['dmd.isDelete', '=', 0],
            ['dmd.wxappUserUuid', '=', $data['uuid']],
            ['dm.isDelete', '=', 0],
        ];

        $list = DB::table('certificate_digitalmachinedriver')
            ->alias('dmd')
            ->leftJoin("{$this->table} dm", 'dm.uuid = dmd.digitalMachineUuid')
            ->where($where)
            ->page((int) $page, (int) $limit)
            ->field(['dmd.wxappUserUuid', 'dm.inDate', 'dm.corpCode', 'dm.name', 'dm.remark', 'dm.uuid', 'dm.machineSn', 'dm.qrCode', 'dm.subtitle'])
            ->order(['dmd.id desc'])
            ->select()->toArray();
        // foreach ($list as $key => $value) {
        // }

        $count = DB::table('certificate_digitalmachinedriver')
            ->alias('dmd')
            ->leftJoin("{$this->table} dm", 'dm.uuid = dmd.digitalMachineUuid')
            ->where($where)
            ->count('dmd.id');

        $data = [
            'list'  => $list,
            'count' => $count,
        ];
        return result(SUCCESS, $data, '');
    }

    public function getType(Request $request)
    {
        $data  = $request->data;
        $where = [
            ['projectCode', '=', $request->prjCode],
            ['isDelete', '=', $data['isDelete'] ?? 0],
        ];
        if (!empty($data['name'])) {
            array_push($where, ['name', 'like', "%" . $data['name'] . "%"]);
        }

        $list = DB::table('certificate_digitalmachinetype')
            ->where($where)
            ->where('level',2)
            ->field(['name', 'uuid', 'subtitle'])
            ->order(['id desc'])
            ->select()->toArray();

        return result(SUCCESS, $list, '');

    }

    /**
     * @Description: 根据设备UUID获取设备的检修列表数据
     * @param {Request} $request
     */
    public function getDigitalMachineBindDigitalMachineRepairList(Request $request)
    {
        $data  = $request->data;
        $limit = $data['limit'] ?? 10;
        $page  = $data['page'] ?? 1;

        $machine = DB::table('certificate_digitalMachine')
            ->alias('m')
            ->join('certificate_digitalMachineType t', 't.uuid = m.digitalMacineTypeUuid')
            ->where(['m.isDelete' => 0, 'm.uuid' => $data['digitalMachineUuid'], 'm.projectCode' => $request->prjCode])
            ->find();

        if (!$machine) {
            return result(FAIL, '', '设备不存在');
        }

        $where = [
            ['dmr.projectCode', '=', $request->prjCode],
            ['dmr.machineUuid', '=', $data['digitalMachineUuid']],
            ['dmr.isDelete', '=', 0],
        ];
        if (!empty($data['title'])) {
            array_push($where, ['dmr.title', 'like', "%" . $data['title'] . "%"]);
        }
        if (isset($data['status'])) {
            if ($data['status'] == 'repairing') {
                array_push($where, ['dmr.status', '=', 0]);
            }
            if ($data['status'] == 'finish') {
                array_push($where, ['dmr.status', '=', 1]);
            }
        }

        $list = DB::table('certificate_digitalmachinerepair')
            ->alias('dmr')
            ->leftJoin('certification_projectWorker pw', 'pw.wxappUserUuid = dmr.wxappUserUuid')
            ->where($where)
            ->page((int) $page, (int) $limit)
            ->field(['dmr.title', 'pw.workerName', 'dmr.inDate', 'dmr.auditTime', 'dmr.status', 'dmr.uuid as digitalMachineRepairUuid', 'dmr.description'])
            ->order(['dmr.id desc'])
            ->select()->toArray();

        foreach ($list as $key => &$value) {
            $value['auditName'] = '';
            if ($value['status'] == 0) {
                continue;
            }
            $where1 = [
                ['dmrr.repairUuid', '=', $value['digitalMachineRepairUuid']],
                ['dmrr.projectCode', '=', $request->prjCode],
                ['dmrr.isDelete', '=', 0],
                ['pw.isDelete', '=', 0],
            ];
            $audit = DB::table('certificate_digitalmachinerepairrecord')
                ->alias('dmrr')
                ->leftJoin('certification_projectWorker pw', 'pw.wxappUserUuid = dmrr.wxappUserUuid')
                ->where($where1)
                ->field(['pw.workerName'])
                ->order(['dmrr.id desc'])
                ->group('dmrr.id')
                ->find();

            $value['auditName'] = isset($audit['workerName']) ? $audit['workerName'] : "";
        }
        unset($value);
        $count = DB::table('certificate_digitalmachinerepair')
            ->alias('dmr')
            ->leftJoin('certification_projectWorker pw', 'pw.wxappUserUuid = dmr.wxappUserUuid')
            ->where($where)
            ->count('dmr.id');

        $data = [
            'list'  => $list,
            'count' => $count,
        ];
        return result(SUCCESS, $data, '');
    }
    /**
     * @Description: 根据检修uuid获取检修record数据
     * @param {Request} $request
     */
    public function getDigitalMachineRepairRecordData(Request $request)
    {
        $data  = $request->data;
        $uuid  = $data['digitalMachineRepairUuid'];
        $where = [
            ['dmr.projectCode', '=', $request->prjCode],
            ['dmr.isDelete', '=', 0],
        ];
        $repair = DB::table("certificate_digitalmachinerepair")
            ->alias('dmr')
            ->leftJoin('certification_projectWorker pw', 'pw.wxappUserUuid = dmr.wxappUserUuid')
            ->where($where)
            ->where('dmr.uuid', $uuid)
            ->field(['dmr.title', 'dmr.description', 'pw.workerName', 'dmr.inDate', 'dmr.auditTime', 'dmr.status', 'dmr.uuid as digitalMachineRepairUuid'])
            ->find();
        $list = DB::table('certificate_digitalmachinerepairrecord')
            ->where('isDelete', 0)
            ->where('repairUuid', $uuid)
            ->field(['uuid', 'wxappUserUuid', 'repairUuid', 'flowOrder', 'formData', 'inDate'])
            ->order(['flowOrder asc'])
            ->select()->toArray();

        $data = [
            'repair'           => $repair,
            'repairRecordlist' => $list,
        ];
        return result(SUCCESS, $data, '');
    }

    /**
     * @Description: 根据设备uuid查询附件列表
     * @param {Request} $request
     */
    public function getDigitalMachineFileList(Request $request)
    {
        $data = $request->data;
        $uuid = $data['digitalMachineUuid'];
        $list = DB::table('certificate_digitalmachinefile')
            ->alias('dmf')
            ->join('certificate_file f', 'f.uuid = dmf.fileUuid')
            ->join('certificate_fileType ft', 'f.uuid = dmf.fileUuid')
            ->where([
                'dmf.isDelete'           => 0,
                'dmf.digitalMachineUuid' => $uuid,
            ])
            ->field(['f.name', 'f.subtitle', 'ft.name as typeName', 'f.effectTime', 'f.expireTime', 'f.uuid'])
            ->order(['dmf.id desc'])
            ->group('f.uuid')
            ->select()->toArray();
        return result(SUCCESS, $list, '');
    }

    /**
     * @Description: 根据文件uuid查询附件详情
     * @param {Request} $request
     */
    public function getFileData(Request $request)
    {
        $data = $request->data;
        $uuid = $data['fileUuid'];
        $data = DB::table('certificate_file')
            ->where('projectCode', $request->prjCode)
            ->where('isDelete', 0)
            ->where('uuid', $uuid)
            ->field(['uuid', 'name', 'expireTime', 'effectTime', 'subtitle', 'inDate', 'file', 'formData', 'fileType'])
            ->order(['id desc'])
        // ->select()->toArray();
            ->find();
        // foreach ($list as $key => &$value) {
        $data['formData'] = json_decode($data['formData'], true);
        // }
        return result(SUCCESS, $data, '');
    }

}
